package com.itheima.tlias84.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias84.controller.po.InsertEmpParam;
import com.itheima.tlias84.controller.po.SelectEmpPageParam;
import com.itheima.tlias84.dao.entity.Emp;
import com.itheima.tlias84.dao.mapper.EmpMapper;
import com.itheima.tlias84.dao.mapper.ExprMapper;
import com.itheima.tlias84.service.EmpService;
import com.itheima.tlias84.service.dto.SelectEmpAndExprDTO;
import com.itheima.tlias84.service.dto.SelectEmpDTO;
import com.itheima.tlias84.service.dto.SelectExprDTO;
import com.itheima.tlias84.service.vo.PageVO;
import com.itheima.tlias84.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    EmpMapper empMapper;

    @Autowired
    ExprMapper exprMapper;

    @Override
    public List<Emp> selectAll() {
        return empMapper.selectAll();
    }

    @Override
    public ResultUtil selectPage(SelectEmpPageParam param) {
        Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SelectEmpDTO> list = empMapper.selectPage(param);
        PageVO<Object> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(list);
        return ResultUtil.success(pageVO);
    }

    @Override
    public SelectEmpAndExprDTO selectById(Integer id) {
        SelectEmpAndExprDTO empAndExprDTO = empMapper.selectById(id);
        List<SelectExprDTO> selectExprDTOS = exprMapper.selectByEmpId(empAndExprDTO.getId());
        empAndExprDTO.setExprList(selectExprDTOS);
        return empAndExprDTO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteEmp(List<Integer> list) {
        int flag = empMapper.deleteEmp(list);
        exprMapper.deleteByEmpId(list);
        return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertEmp(@Param("param") InsertEmpParam param) {

        int i = empMapper.insertEmp(param);
        log.info("插入主键{}", param.getId());

        if (Objects.nonNull(param.getExprList()) && !param.getExprList().isEmpty()) {
        exprMapper.batchInsert(param.getExprList(), param.getId());
        }
        return i;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateEmp(InsertEmpParam param) {
        int i = empMapper.updateEmp(param);
        exprMapper.deleteByEmpId(List.of(param.getId()));
        if (Objects.nonNull(param.getExprList()) && !param.getExprList().isEmpty()) {
            exprMapper.batchInsert(param.getExprList(), param.getId());
        }

        return i;
    }


}